import express from "express";
import fs from "fs";
import path from "path";
import { MyFileDir } from "../../model/models/MyFileDirTable";
import { getIpAddress } from "../../utils/getIp";
import { PORT, VideoExt, ImgExt, staticPath, staticPathName } from "../../utils/const";
import { CODE } from "../../utils/const";
import { ReturnData, MyFileDirItf } from "../../interface/interface";
import { Op } from "sequelize";
import { asyncHandler } from "../middleware/asyncHandler"

const router = express.Router();

router.get("/getVideo/:id", asyncHandler( async (req, res) => {
    let ip = getIpAddress();
    let hostPost = `http://${ip}:${PORT}/static`;
    let { dataValues } = (await MyFileDir.findByPk((req.params as any).id))!;
    let data = dataValues as MyFileDirItf;
    let arr = data.path.split("/");
    data.fileName = arr[arr.length - 1];
    data.relativePath = data.path;
    data.thumbnailPath = `${hostPost}${data.thumbnailPath.trim()}`;
    data.path = `${hostPost}${data.path.trim()}`;
    return data
} ));

router.get(" ", async (req, res) => {
    let filePath = path.resolve(__dirname, "../../../../mp4/v0300fg10000ch91opjc77u1s39urahg.MP4");
    let stat = fs.statSync(filePath); //获取文件信息
    let fileSize = stat.size;
    let range = req.headers.range;

    if (range) {
        //有range头才使用206状态码

        let parts = range.replace(/bytes=/, "").split("-");
        let start = parseInt(parts[0], 10);
        let end = parts[1] ? parseInt(parts[1], 10) : start + 9999999;

        // end 在最后取值为 fileSize - 1
        end = end > fileSize - 1 ? fileSize - 1 : end;

        let chunksize = end - start + 1;
        let file = fs.createReadStream(filePath, { start, end });
        let head = {
            "Content-Range": `bytes ${start}-${end}/${fileSize}`,
            "Accept-Ranges": "bytes",
            "Content-Length": chunksize,
            "Content-Type": "video/mp4",
        };
        res.writeHead(206, head);
        file.pipe(res); //Node中的Server端HTTP response是Writable流
    } else {
        let head = {
            "Content-Length": fileSize,
            "Content-Type": "video/mp4",
        };
        res.writeHead(200, head);
        fs.createReadStream(filePath).pipe(res);
    }
});

export default router;
